package 康复训练_JavaGo并驾齐驱;

import 二叉树.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Jz32III从上到下打印二叉树III {

    public List<List<Integer>> levelOrder(TreeNode root) {

        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.addLast(root);
        boolean leftOrder = true;

        while (!queue.isEmpty()) {
            Deque<Integer> itemList = new ArrayDeque<>();
            int count = queue.size();
            while (count > 0) {
                count--;
                TreeNode firstNode = queue.removeFirst();
                if (leftOrder) {
                    itemList.addLast(firstNode.val);
                } else {
                    itemList.addFirst(firstNode.val);
                }
                if (firstNode.left != null) {
                    queue.addLast(firstNode.left);
                }
                if (firstNode.right != null) {
                    queue.addLast(firstNode.right);
                }
            }
            leftOrder = !leftOrder;
            result.add(new ArrayList<>(itemList));
        }

        return result;
    }

}
